package com.qingyun.cameralab.views

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin

class PieChartView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {

    private val piePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }

    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
        color = Color.BLACK
        textSize = 40f
        textAlign = Paint.Align.CENTER
    }

    private var data: List<PieChartData> = emptyList()
    private var totalValue = 0f
    private val rectF = RectF()

    fun setData(newData: List<PieChartData>) {
        data = newData.filter { it.value > 0 }
        totalValue = data.sumOf { it.value.toDouble() }.toFloat()
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (data.isEmpty()) return

        val size = min(width, height) - paddingLeft - paddingRight
        val left = paddingLeft + (width - size) / 2f
        val top = paddingTop + (height - size) / 2f
        rectF.set(left, top, left + size, top + size)
        val radius = size / 2f

        var startAngle = -90f // 从12点方向开始

        data.forEach { item ->
            val sweepAngle = (item.value / totalValue) * 360
            drawArc(canvas, item, startAngle, sweepAngle, radius)
            drawLabel(canvas, item, startAngle, sweepAngle, radius)
            startAngle += sweepAngle
        }
    }

    private fun drawArc(
        canvas: Canvas,
        item: PieChartData,
        startAngle: Float,
        sweepAngle: Float,
        radius: Float,
    ) {
        piePaint.color = item.color
        canvas.drawArc(rectF, startAngle, sweepAngle, true, piePaint)
    }

    private fun drawLabel(
        canvas: Canvas,
        item: PieChartData,
        startAngle: Float,
        sweepAngle: Float,
        radius: Float
    ) {
        val middleAngle = startAngle + sweepAngle / 2
        val angleInRad = Math.toRadians(middleAngle.toDouble())

        // 根据扇区位置动态调整标签方向
        val isRightHemisphere = middleAngle in 0f..180f
        val labelRadius = if (isRightHemisphere) radius * 1.35f else radius * 0.85f

        // 计算文字位置
        val centerX = width / 2f
        val centerY = height / 2f
        val x = centerX + cos(angleInRad).toFloat() * labelRadius
        val y = centerY + sin(angleInRad).toFloat() * labelRadius

        // 动态计算文字对齐方式和旋转角度
        val (textAlign, textRotation, textOffset) = when {
            isRightHemisphere -> {
                val rotation = if (middleAngle < 90f) middleAngle - 90f else middleAngle + 90f
                Triple(
                    if (middleAngle < 90f) Paint.Align.LEFT else Paint.Align.RIGHT,
                    rotation,
                    if (middleAngle < 90f) 8f else -8f
                )
            }
            else -> {
                val rotation = if (middleAngle < 270f) middleAngle + 90f else middleAngle - 90f
                Triple(
                    if (middleAngle < 270f) Paint.Align.RIGHT else Paint.Align.LEFT,
                    rotation,
                    if (middleAngle < 270f) -8f else 8f
                )
            }
        }

        // 文字基线计算优化
        val fontMetrics = textPaint.fontMetrics
        val verticalOffset = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom

        // 绘制背景（带方向箭头）
        val textWidth = textPaint.measureText(item.label)
        val bgRect = when(textAlign) {
            Paint.Align.LEFT -> RectF(x, y - 30f, x + textWidth + 24f, y + 30f)
            Paint.Align.RIGHT -> RectF(x - textWidth - 24f, y - 30f, x, y + 30f)
            else -> RectF(x - textWidth/2 - 12f, y - 30f, x + textWidth/2 + 12f, y + 30f)
        }

        canvas.save()
        canvas.rotate(textRotation, x, y)

        // 绘制方向指示线
        val lineLength = if (isRightHemisphere) 40f else -40f
        canvas.drawLine(
            x + textOffset,
            y,
            x + textOffset + lineLength,
            y,
            textPaint.apply {
                color = item.color
                strokeWidth = 4f
            }
        )

        // 绘制背景框
        textPaint.color = Color.WHITE
        canvas.drawRoundRect(bgRect, 15f, 15f, textPaint)

        // 绘制文字
        textPaint.color = Color.BLACK
        canvas.drawText(
            item.label,
            x + textOffset + when(textAlign) {
                Paint.Align.LEFT -> 20f
                Paint.Align.RIGHT -> -20f
                else -> 0f
            },
            y + verticalOffset,
            textPaint.apply { this.textAlign = textAlign }
        )

        canvas.restore()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val minSize = (textPaint.textSize * 5).toInt()
        val desiredWidth = resolveSize(minSize, widthMeasureSpec)
        val desiredHeight = resolveSize(minSize, heightMeasureSpec)
        setMeasuredDimension(desiredWidth, desiredHeight)
    }
}